/**
 * Created with JetBrains PhpStorm.
 * User: vander
 * Date: 6/13/13
 * Time: 9:31 PM
 * To change this template use File | Settings | File Templates.
 */

var Collections = Class.create({
    initialize: function(){
        this.books = new Array();
        this.selectedBookIdToDelete = null;
    },
    load: function(o){
        //o --> collections json object
        var _this = this;
        this.books.clear();
        $j.each(o.books, function(index, value){
            var bookInfo = new Object();

            $j.each(value, function(key, val){
                bookInfo[key] = val;
            });

            _this.books.push(bookInfo);
        });

        $j("#" + Static.collectionsList).empty();

        $j.each(_this.books, function(index, value){
            var liTag = new Element("li", {bookId: value.bookId});
            var img = $j("<img>").attr('src', Static.serverPath + value.resourcesPath + value.coverImage).attr({width: "80", height: "80"});
            var aTag = $j("<a></a>").append(img).append(value.name);
            var splitaTag = $j("<a href='#deleteConfirm' data-rel='popup'>Remove</a>");

            $j(splitaTag).on("click", function(){
                _this.selectedBookIdToDelete = value.bookId;
            });
//               var splitaTag = $j("<a href='#popss' data-rel='popup'>Setting</a>");

//            $j(aTag).on("click", function(){
//                if(!Global.collections.isInCollections(value.bookId)){
//                    Global.downloading.add(value);
//                    $j.mobile.changePage("#downloading");
//                }
//            });

            $j(liTag).append(aTag).append(splitaTag).appendTo("#" + Static.collectionsList);
        });

        $j("#" + Static.collectionsList).listview("refresh");
    },
    remove: function(bookId){
        for(var i = 0; i < this.books.length; i++){
            if(this.books[i].bookId == bookId){
                var liTag = $j("#"+Static.collectionsList + " li[bookId=" + bookId +"]");
                $j(liTag).remove();

                this.books[i] = null;
                this.books = this.books.compact();
                $j("#"+Static.collectionsList).listview("refresh");
                break;
            }
        }
    }
});
